import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class CalculatorSingle extends JFrame {
    private JTextField display;
    private JTextArea history;
    private double currentNumber;
    private String operator;
    private boolean isNewEntry;
    private StringBuilder currentExpression;

    public CalculatorSingle() {
        super("简易计算器");
        setSize(260, 350); // 设置初始窗口大小
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示窗口
        setResizable(false); // 禁止窗口大小调整
        currentNumber = 0.0;
        operator = "=";
        isNewEntry = true;
        currentExpression = new StringBuilder();
        initUI();
    }

    private void initUI() {
        display = new JTextField();
        display.setEditable(false);
        display.setHorizontalAlignment(SwingConstants.RIGHT);
        Font font = new Font("Arial", Font.PLAIN, 35);
        display.setFont(font);

        history = new JTextArea();
        history.setEditable(false);
        history.setLineWrap(true);
        history.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(history);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(5, 4, 5, 5));
        String[] buttons = {
                "7", "8", "9", "/",
                "4", "5", "6", "*",
                "1", "2", "3", "-",
                "0", ".", "=", "+",
                "C"  // 清零按钮
        };
        for (String b : buttons) {
            JButton button = new JButton(b);
            if (b.equals("C")) {
                button.addActionListener(e -> clearAll());
            } else {
                button.addActionListener(e -> handleButtonClick(b));
            }
            panel.add(button);
        }

        add(display, BorderLayout.NORTH);
        add(panel, BorderLayout.CENTER);
        add(scrollPane, BorderLayout.SOUTH);

        // 添加键盘监听器
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                char c = e.getKeyChar();
                if (Character.isDigit(c) || c == '.') {
                    handleKeyInput(Character.toString(c));
                } else if (c == '+' || c == '-' || c == '*' || c == '/') {
                    handleOperatorClick(String.valueOf(c));
                } else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    calculateResult();
                } else if (e.getKeyCode() == KeyEvent.VK_C && e.isControlDown()) {
                    clearAll();
                }
            }
        });
        setFocusable(true); // 确保窗口可以接收键盘事件
        display.requestFocus(); // 将焦点设置到显示区域
    }

    private void handleButtonClick(String command) {
        if (command.matches("[0-9.]")) {
            handleKeyInput(command);
        } else {
            handleOperatorClick(command);
        }
    }

    private void handleKeyInput(String input) {
        if (isNewEntry) {
            display.setText(input);
            isNewEntry = false;
        } else {
            display.setText(display.getText() + input);
        }
        if (operator.equals("=")) {
            currentExpression.append(display.getText());
        } else {
            currentExpression.append(display.getText()).append(" ").append(operator).append(" ");
        }
    }

    private void handleOperatorClick(String op) {
        if (!operator.equals("=")) {
            calculateResult();
        }
        currentNumber = Double.parseDouble(display.getText());
        operator = op;
        isNewEntry = true;
        currentExpression.append(display.getText()).append(" ").append(operator).append(" ");
    }

    private void calculateResult() {
        double result = 0;
        try {
            switch (operator) {
                case "+":
                    result = currentNumber + Double.parseDouble(display.getText());
                    break;
                case "-":
                    result = currentNumber - Double.parseDouble(display.getText());
                    break;
                case "*":
                    result = currentNumber * Double.parseDouble(display.getText());
                    break;
                case "/":
                    if (Double.parseDouble(display.getText()) == 0) {
                        throw new ArithmeticException("除数不能为零");
                    }
                    result = currentNumber / Double.parseDouble(display.getText());
                    break;
            }
            display.setText("" + result);
            operator = "=";
            isNewEntry = true;

            // 将当前计算式添加到历史记录
            currentExpression.append(display.getText());
            history.append(currentExpression.toString() + "\n");
            currentExpression = new StringBuilder(); // 重置表达式
        } catch (ArithmeticException e) {
            display.setText("错误: " + e.getMessage());
        }
    }

    private void clearAll() {
        display.setText("");
        currentNumber = 0.0;
        operator = "=";
        isNewEntry = true;
        currentExpression = new StringBuilder();
        history.setText(""); // 清空历史记录
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            CalculatorSingle calculator = new CalculatorSingle();
            calculator.setVisible(true);
        });
    }
}